const http = require('http');
// const URL = require('URL');
const Socket = require('socket.io');
const Ctrl = require('./controller/user');
const svgCaptcha = require('svg-captcha');
const session = require('nodejs-session-manager');
const qs = require('qs');
// session.init();

require('./db/mongoose');
const app = http.Server((req, res) => {
  const ctrl = new Ctrl(req, res);
  const reqObj = new URL(req.url, 'http://localhost');
  const query = qs.parse(reqObj.search, { ignoreQueryPrefix: true });
  // 设置允许跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 预设返回内容类型
  res.setHeader('Content-Type', 'application/json;charset=UTF-8');

  // 非登录相关的接口都需要校验token
  if(!reqObj.pathname.startsWith('/login') && !ctrl.checkToken()) {
    return false;
  }
  // ctrl.addAUser();
  // 获取好友列表接口
  if(reqObj.pathname === '/chat/getFriendList') {
    ctrl.getFriends()
    // res.end(JSON.stringify({}));
  // 用户登录接口
  }else if (reqObj.pathname === '/login/userlogin') {
    // console.log(req);
    // 执行登录/注册逻辑
    ctrl.loginAction()
  // 获取验证码接口
  }else if (reqObj.pathname === '/login/getCheckSvg') {
    console.log(req.headers['x-forwarded-for']);
    let captcha = svgCaptcha.create();
    session.createSession(captcha.text, req.headers['x-forwarded-for'])
    res.setHeader('Content-Type', 'image/svg+xml');
    res.end(captcha.data);
  }else if (reqObj.pathname === '/user/getUserInfo') {
    ctrl.getUserInfo(query);
  }else{
    // res.writeHead('Content-Type', 'application/json;charset=UTF-8');
    res.end(JSON.stringify({code: -1, status: false, message: '没有这个接口哦！'}));
  };
});

const io = Socket(app, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});
io.on('connection', (socket) => {
  console.log('a user connected');
  // socket.on('hall_chat', (res) => {
  //   console.log(res)
  //   socket.broadcast.emit('hall_chat', {some: res});
  // })
  socket.onAny((eventName, ...args) => {
    console.log(eventName, args[0])
    let msg = JSON.parse(args[0]);
    for(var key in msg) {
      msg[key].new = 1;
    }
    socket.broadcast.emit(eventName, {some: JSON.stringify(msg)});
  })
})

app.listen(9527, () => {
  console.log('server run in port 9527')
})